package main

import (
	Mysql "gin/database"
	"gin/model"
	"gin/response"
	"github.com/spf13/viper"
	"log"
	"os"
)

func main() {
	InitConfig()
	Mysql.InitDB()

	testFind()
	testSelect()
	testDelete()
	testFindById()
	testCreate()
	testUpdate()
	testInsertAll()
}

func testInsertAll() {
	test := []model.Test{
		{
			Name: "test哦1",
			Code: "test001",
		},
		{
			Name: "test哦2",
			Code: "test002",
		},
		{
			Name: "test哦3",
			Code: "test003",
		},
		{
			Name: "test哦4",
			Code: "test004",
		},
	}
	rows, err := model.InsertAll(&model.Test{}, test)
	if err != nil {
		log.Println(err.Error())
		return
	}
	println(rows)
}

func testUpdate() {
	var test model.Test

	updateFields := map[string]interface{}{
		"id":   1,
		"name": "test",
		"code": "test",
	}
	filter := map[string]interface{}{
		"eq": map[string]interface{}{
			"condition": "id = ?",
			"val":       1,
		},
	}
	_, err := model.Update(&test, filter, updateFields)
	if err != nil {
		log.Println(err.Error())
		return
	}
	println(test.Name)
}

func testCreate() {
	var test model.Test
	test.Name = "test001"
	test.Code = "code001"

	err := model.Insert(&test)
	if err != nil {
		log.Println(err.Error())
		return
	}
	println(test.Name)
}

func testFindById() {
	var Test model.Test

	err := model.FindById(&Test, 1, nil)
	if err != nil {
		log.Println(err.Error())
		return
	}
	println(Test.Name)
}

func testDelete() {
	var Test model.Test
	//err := model.Find(&Test, map[string]interface{}{
	//	"-eq": map[string]interface{}{
	//		"condition": "id > ?",
	//		"val":       0,
	//	}})
	rows, err := model.Delete(&Test, map[string]interface{}{
		"eq": map[string]interface{}{
			"condition": "id = ?",
			"val":       "99",
		},
	})
	if err != nil {
		log.Println(err.Error())
		return
	}
	println(rows)
}

func testFind() {
	var Test model.Test
	//err := model.Find(&Test, map[string]interface{}{
	//	"-eq": map[string]interface{}{
	//		"condition": "id > ?",
	//		"val":       0,
	//	}})
	err := model.Find(&Test, map[string]interface{}{}, nil)
	if err != nil {
		log.Println(err.Error())
		return
	}
	println()
}

func testSelect() {
	var Test model.Test
	//err := model.Find(&Test, map[string]interface{}{
	//	"-eq": map[string]interface{}{
	//		"condition": "id > ?",
	//		"val":       0,
	//	}})
	var result response.SelectResp
	rows := make([]model.Test, 0)
	result.Rows = &rows

	err := model.Select(&Test, &result, map[string]interface{}{
		"-eq": map[string]interface{}{
			"condition": "id > ?",
			"val":       1,
		},
	}, 10, 0, "", "", nil)
	if err != nil {
		log.Println(err.Error())
		return
	}
	println()
}

func InitConfig() {
	workDir, _ := os.Getwd()
	viper.SetConfigName("application")
	viper.SetConfigType("yml")
	viper.AddConfigPath(workDir + "/config")
	err := viper.ReadInConfig()
	if err != nil {
		panic(err)
	}
}
